<?php

namespace app\admin\service;

use EasyWeChat\Factory;
use think\admin\Service;
use think\facade\Log;

/**
 * 企业微信收钱登录
 * Class WxWorkOAuthService
 * @package app\admin\service
 */
class WxWorkOAuthService extends Service
{
    /**
     * 配置参数
     * @var array
     */
    private $config;
    private $contacts;

    /**
     * 接口服务初始化
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function initialize()
    {
        $this->config = config('office_work');
        $this->config = [
            'corp_id' => $this->config['corp_id'],
            'secret' => $this->config['agent_secret'],
            'agent_id' => $this->config['agent_id'],
        ];
        $this->contacts = Factory::work($this->config);
    }

    /**
     * 授权登录回调
     * @return void
     */
    public function oauthRedirect()
    {
        // $callbackUrl 为授权回调地址
        $callbackUrl = getHttpHost(true); // 需设置可信域名
        $callbackUrl = urlencode($callbackUrl);

        // 返回一个 redirect 实例

        $url = getHttpHost() . "/admin/api.WxWork/oauthCallback?&callback=$callbackUrl";
        $redirect =  $this->contacts->oauth->redirect($url);

        // 获取企业微信跳转目标地址
        $targetUrl = $redirect->getTargetUrl();

        $redirect->send();
    }

    /**
     * 返回授权的userid
     * @return mixed|string|null
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Overtrue\Socialite\Exceptions\AuthorizeFailedException
     */
    public function getUserid()
    {
        $code = request()->get('code', '');
        $this->contacts = Factory::work($this->config);
        $user = $this->contacts->oauth->detailed()->userFromCode($code);

        return $user->getId();
    }
}